﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;

namespace MBBHotelReservation
{
    public partial class frmServiceDetails : Form
    {
        UnityProcessor proc = new UnityProcessor();
        Threader t = new Threader();
        UnityScript[] dat = new UnityScript[0];
        UnityScript[] udet;
        UnityElement eldet;
        //List Buffers
        float[][] price = new float[0][];
        string filter, service, transNumber;
        bool isLoad = false;
        //Data Buffers
        List<frmTransactionsManager.TransactionItemDetailType> _data = new List<frmTransactionsManager.TransactionItemDetailType>();

        public frmServiceDetails()
        {
            InitializeComponent();
            DoInitialize();
            DoEvents();
            DoUnityEvents();
        }
        void DoInitialize()
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }
        void DoUnityEvents()
        {
            proc.ProcessCompleted += new ProcessHandler(delegate(string id, string desc)
            {
                t.SafeCall(this, delegate
                {
                    switch (id)
                    {
                      
                        case "LOADROOMS":
                            
                            proc.DBPUX_Data_Fetch(out dat);
                            if (dat[0].Data_Count > 0)
                            {
                                dat[0].Data_Get(0, out eldet);

                                lstType.Items.Clear();
                                lstType.Items.AddRange(dat[0].ToList<string>(0));
                                price[0] = dat[0].ToList<float>(1);
                                if (price.Length == 3)
                                {
                                    price[1] = dat[0].ToList<float>(2);
                                    price[2] = dat[0].ToList<float>(3);
                                }
                                if (isLoad)
                                {
                                    lstType.Text = _data[1].StringData;
                                    lstPrice.Text = _data[2].NumericData.ToString();
                                    isLoad = false;
                                }
                            }
                            else
                            {
                                lstType.Items.Clear();
                            }
                            this.Enabled = true;

                            break;
                        case "LOADFOOD":
                        
                        case "LOADDETAILS":

                            proc.DBPUX_Data_Fetch(out dat);
                            
                            //dat[0].Data_Get(0, out eldet);

                            if (lstCat.Text == "ROOMS")
                            {
                                txtBuilding.Items.Clear();
                                txtBuilding.Items.AddRange(dat[0].ToList<string>(0));
                            }
                            else
                            {
                                txtBuilding.Items.Clear();
                                lstType.Items.Clear();
                                lstType.Items.AddRange(dat[0].ToList<string>(0));
                                price[0] = dat[0].ToList<float>(1);
                                if (price.Length == 3)
                                {
                                    price[1] = dat[0].ToList<float>(2);
                                    price[2] = dat[0].ToList<float>(3);
                                }
                                if (isLoad)
                                {
                                    lstType.Text = _data[1].StringData;
                                    lstPrice.Text = _data[2].NumericData.ToString();
                                    isLoad = false;
                                }
                            }
                            this.Enabled = true;
                            break;
                    }
                });
            });
            proc.ProcessError += new ProcessHandler(delegate(string id, string desc)
            {
                t.SafeCall(this, delegate
                {
                    MessageBox.Show(desc);
                    this.Enabled = true;
                });
            });
        }
        void DoEvents()
        {
            this.Load += new EventHandler(delegate
            {
                if (service.Equals("FOOD"))
                {
                    this.Enabled = false;
                    UnityScript u = new UnityScript("LOADFOOD", 2);
                    u.Script_Add(Script.DBPUX_BEGIN);
                    u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblfoodlookup ORDER BY fFood ASC");
                    price = new float[][]
                    {
                        new float[0],
                    };
                    u.Script_Add(Script.DBPUX_COMMIT);
                    proc.Run(u);
                }
                
            });

            this.Shown += new EventHandler(delegate
            {
                if (isLoad) lstCat.Text = _data[0].StringData;
                if (service.Equals("CHECKOUT") || service.Equals("ACTUALCHECKOUT") )
                {
                    optional.Enabled = false;
                }
                else if (service.Equals("AMENITIES"))
                {
                    optional.Enabled = false;
                    txtBuilding.Enabled = false;
                   
                }
                else if (service.Equals("FOOD"))
                {
                    servingTime.Enabled = true;
                    optional.Enabled = false;
                    txtBuilding.Enabled = false;
                    lstCat.Enabled = false;
                }
            });
            btnAdd.Click += new EventHandler(delegate(object sender, EventArgs e)
            {
                lstOccupants.Items.Add(txtOccupants.Text);
                txtOccupants.Text = "";
                txtOccupants.Focus();
            });
            btnRemove.Click += new EventHandler(delegate(object sender, EventArgs e)
            {
                if (lstOccupants.SelectedIndex > -1)
                {
                    lstOccupants.Items.RemoveAt(lstOccupants.SelectedIndex);
                }
            });
            btnOk.Click += new EventHandler(delegate(object sender, EventArgs e)
            {
                _data = new List<frmTransactionsManager.TransactionItemDetailType>();
                // x variable was used for the buf to increase the size by 1 if it is food 
                int x =0 ;
                if (service.Equals("FOOD")) x = 1;
                if (service.Equals("AMENITIES") && lstCat.Text.Equals("BRIDAL CAR") && lstType.Text.Equals("CAR RENTAL")) x = x + 7;
                if (service.Equals("AMENITIES") && lstCat.Text.Equals("BRIDAL CAR") && lstType.Text.Equals("AIRPORT CAR RENTAL")) x = x + 14;

                frmTransactionsManager.TransactionItemDetailType[] buf = new frmTransactionsManager.TransactionItemDetailType[3 + lstOccupants.Items.Count+ x];
                
                buf[0].KeyID = "CATEGORY";
                buf[0].StringData = lstCat.Text;
                if (service.Equals("FOOD"))
                {
                    buf[0].StringData = "FOOD";
                }
                buf[1].KeyID = "TYPE";
                buf[1].StringData = lstType.Text;
                
                if (lstPrice.Text != "")
                {
                    buf[2].KeyID = "ORIG_PRICE";
                    buf[2].NumericData = float.Parse(lstPrice.Text);

                }
                
                if (!service.Equals("FOOD"))
                {
                    if (service.Equals("AMENITIES"))
                    {
                        if (lstCat.Text.Equals("BRIDAL CAR"))
                        {
                            buf[3].KeyID = "DATE";
                            buf[3].DateTimeData = DateTime.Parse(txtDate.Text);

                            buf[4].KeyID = "CARTYPE";
                            buf[4].StringData = txtVehicle.Text;

                            buf[5].KeyID = "DESTINATION";
                            buf[5].StringData = txtDestination.Text;

                            buf[6].KeyID = "LEAVE";
                            buf[6].DateTimeData = DateTime.Parse(leaveDateTime.Text);

                            buf[7].KeyID = "RETURN";
                            buf[7].DateTimeData = DateTime.Parse(returnDateTime.Text);

                            buf[8].KeyID = "DRIVER";
                            buf[8].StringData = txtDriver.Text;

                            buf[9].KeyID = "NPERSON";
                            buf[9].NumericData = (float)nPerson.Value;

                            if (!lstType.Text.Equals("CAR RENTAL"))
                            {
                                buf[10].KeyID = "ClientName";
                                buf[10].StringData = txtClientName.Text;

                                buf[11].KeyID = "AirportType";
                                buf[11].StringData = txtAirport.Text;

                                buf[12].KeyID = "Terminal";
                                buf[12].StringData = txtTerminal.Value.ToString();

                                buf[13].KeyID = "AirLine";
                                buf[13].StringData = txtAirlineName.Text;

                                buf[14].KeyID = "FlightNumber";
                                buf[14].StringData = txtFlightNumber.Text;

                                buf[15].KeyID = "Arrival";
                                buf[15].DateTimeData = DateTime.Parse(txtArrival.Text);

                                buf[16].KeyID = "Departure";
                                buf[16].DateTimeData = DateTime.Parse(txtDeparture.Text);
                            }
                        }
                    }

                    if (lstCat.Text == "" || lstType.Text == "")
                    {
                        buf[1].StringData = "No details";
                        buf[2].KeyID = "ORIG_PRICE";
                        buf[2].NumericData = 0f;
                    }

                    for (int i = 3; i < 3 + lstOccupants.Items.Count; i++)
                    {
                        buf[i].KeyID = "OCCUPANTS";
                        buf[i].StringData = lstOccupants.Items[i - 3].ToString();
                    }
                }
                else
                {
                    buf[3].KeyID = "SERVING_TIME";
                    buf[3].StringData = servingTime.Text;
                }
                    _data.AddRange(buf);
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            });

            lstCat.SelectedIndexChanged += new EventHandler(delegate
            {
                this.Enabled = false;
                
                UnityScript u = new UnityScript("LOADDETAILS", 2);
                u.Script_Add(Script.DBPUX_BEGIN);
                if (lstCat.Text == "ROOMS")
                {
                    u.Script_Add(Script.DBPUX_QUERY, "SELECT DISTINCT fBuildingName FROM tblroomlookup");
                }
                else if (lstCat.Text == "FUNCTION HALL")
                {
                    // (fCheckInDateTime <= '" + filter + "' AND fCheckOutDateTime >= '" + filter + "') AND 
                    if (service.Equals("RESERVATION"))
                    {
                        u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fFunctionHall, fRate, fStamp FROM tblfunctionlookup WHERE " +
                            "fFunctionHall NOT IN (SELECT fRoom FROM tblmonitoring WHERE " +
                            "fTransactionMode = 'Occupied' OR fTransactionMode = 'Reserve' OR fTransactionMode = 'Maintenance'  OR fTransactionMode = 'HouseKeeping') " +
                            "ORDER BY fFunctionHall ASC");
                    }
                    else if (service.Equals("CHECKIN"))
                    {
                        u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fFunctionHall, fRate, fStamp FROM tblfunctionlookup WHERE " +
                            "fFunctionHall NOT IN (SELECT fRoom FROM tblmonitoring WHERE " +
                            "fTransactionMode = 'Occupied' OR fTransactionMode = 'Maintenance'  OR fTransactionMode = 'HouseKeeping') " +
                            "ORDER BY fFunctionHall ASC");
                    }
                    else
                    {
                        u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fFunctionHall, fRate, fStamp FROM tblfunctionlookup WHERE " +
                            "fFunctionHall IN (SELECT fRoom FROM tblmonitoring WHERE " +
                            "fTransactionMode = 'Occupied' OR fTransactionMode = 'Reserve' OR fTransactionMode = 'Maintenance'  OR fTransactionMode = 'HouseKeeping') " +
                            "ORDER BY fFunctionHall ASC");
                    }
                    price = new float[][]
                    {
                        new float[0],
                    };
                }
                else
                {
                        u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fName, fPrice, fStamp FROM tblamenitieslookup WHERE " +
                            "fCategory = '"+lstCat.Text+"' ORDER BY fName ASC");
                        price = new float[][]
                    {
                        new float[0],
                    };
                }
                u.Script_Add(Script.DBPUX_COMMIT);
                proc.Run(u);
            });
            //additional for rooms
            txtBuilding.SelectedIndexChanged += new EventHandler(delegate
            {
                this.Enabled = false;
                UnityScript u = new UnityScript("LOADROOMS", 2);
                u.Script_Add(Script.DBPUX_BEGIN);
                    //Debug Note : To solve reservations that can't check in.
                    //if (service.Equals("CHECKIN") || service.Equals("RESERVATION"))
                    //XCoder
                    if (service.Equals("RESERVATION"))
                    {
                        //(fCheckInDateTime <= '" + filter + "' AND fCheckOutDateTime >= '" + filter + "') OR
                        u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fRoomNumber, fDayRate, fNightRate, f24HoursRate, fBuildingName, fStamp FROM tblroomlookup WHERE " +
                            "fRoomNumber NOT IN (SELECT fRoom FROM tblmonitoring WHERE " +
                            "fTransactionMode = 'Occupied' OR fTransactionMode = 'Reserve' OR fTransactionMode = 'Maintenance'  OR fTransactionMode = 'HouseKeeping') AND fBuildingName = '"+txtBuilding.Text+"'" +
                            "ORDER BY fRoomNumber ASC");
                        price = new float[][]
                        {
                            new float[0],
                            new float[0],
                            new float[0]
                        };
                    }
                    else if (service.Equals("CHECKIN"))
                    {
                        u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fRoomNumber, fDayRate, fNightRate, f24HoursRate, fBuildingName, fStamp FROM tblroomlookup WHERE " +
                           "fRoomNumber NOT IN (SELECT fRoom FROM tblmonitoring WHERE " +
                           "fTransactionMode = 'Occupied' OR fTransactionMode = 'Maintenance'  OR fTransactionMode = 'HouseKeeping') AND fBuildingName = '" + txtBuilding.Text + "'" +
                           "ORDER BY fRoomNumber ASC");
                        price = new float[][]
                        {
                            new float[0],
                            new float[0],
                            new float[0]
                        };
                    }
                    else
                    {
                        u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fRoomNumber, fDayRate, fNightRate, f24HoursRate, fStamp FROM tblroomlookup WHERE " +
                            "fRoomNumber IN (SELECT fRoom FROM tblmonitoring WHERE " +
                            "(fTransactionMode = 'Occupied' OR fTransactionMode = 'Reserve' OR fTransactionMode = 'Maintenance'  OR fTransactionMode = 'HouseKeeping') AND (fBuildingName = '" + txtBuilding.Text + "' AND fTransNum = '" + transNumber + "')) " +
                            "ORDER BY fRoomNumber ASC");
                        price = new float[][]
                        {
                            new float[0],
                            new float[0],
                            new float[0]
                        };
                    }
                
                u.Script_Add(Script.DBPUX_COMMIT);
                proc.Run(u);
            });

            lstType.SelectedIndexChanged += new EventHandler(delegate
            {
                if (lstType.Text.Equals("AIRPORT CAR RENTAL"))
                {
                    bridalForm.Enabled = true;
                    panel1.Enabled = true;
                }
                else if (lstType.Text.Equals("CAR RENTAL"))
                {
                    bridalForm.Enabled = true;
                    panel1.Enabled = false;
                }

                lstPrice.Items.Clear();
                lstPrice.Items.Add(price[0][lstType.SelectedIndex]);
                if (price.Length == 3)
                {
                    lstPrice.Items.Add(price[1][lstType.SelectedIndex]);
                    lstPrice.Items.Add(price[2][lstType.SelectedIndex]);
                }
            });

        }

        public void SetLists(string[] cats, string filters, string services, string transNum)
        {
            
            lstCat.Items.AddRange(cats);
            filter = filters;
            service = services;
            transNumber = transNum;
        }
        public List<frmTransactionsManager.TransactionItemDetailType> Details
        {
            get { return _data; }
            set 
            { 
                _data = value;
                isLoad = true;
            }
        }
    }
}
